package com.swhysc.information.dao.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.swhysc.information.common.dao.IBaseDao;
import com.swhysc.information.common.model.GridView;
import com.swhysc.information.common.model.PageAble;
import com.swhysc.information.common.utils.MapToBeanUtils;
import com.swhysc.information.dao.IInformationDataColumnExDao;
import com.swhysc.information.service.impl.InformationDataDirExServiceImpl;
import com.swhysc.information.service.impl.InformationDataTableExServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author zmq
 * @Date 2022/10/17 16:48
 * @Description
 */
@Repository
public class InformationDataColumnExDaoImpl implements IInformationDataColumnExDao {
    @Autowired
    private IBaseDao baseDao;

    @Autowired
    private InformationDataTableExServiceImpl informationDataTableService;

    @Autowired
    private InformationDataDirExServiceImpl informationDataDirExService;

    private String TABLE_SQL = "select A.* ,  B.name as data_source_name  " +
            " from INFORMATION_DATA_TABLE_EX A " +
            " left join INFORMATION_DATA_DIRECTORY_EX B on A.data_source_id =  B.id ";

    private String COLUMN_SQL = "select A.* ,  B.name as data_source_name ,  C.en_name as col_en_name , C.ch_name as col_ch_name " +
            " from INFORMATION_DATA_COLUMN_EX C " +
            " left join INFORMATION_DATA_TABLE_EX A on C.table_id = A.id  " +
            " left join INFORMATION_DATA_DIRECTORY_EX B on A.data_source_id =  B.id ";

    private String TABLE_AND_COLUMN_SQL = "select * from ( select A.* ,  B.name as data_source_name ,  C.en_name as col_en_name , C.ch_name as col_ch_name " +
            " from INFORMATION_DATA_COLUMN_EX C " +
            " left join INFORMATION_DATA_TABLE_EX A on C.table_id = A.id  " +
            " left join INFORMATION_DATA_DIRECTORY_EX B on A.data_source_id =  B.id " +
            " ### ) " +
            " union all " +
            " select * from ( select A.* ,  B.name as data_source_name ,null as col_en_name , null as col_ch_name " +
            " from INFORMATION_DATA_TABLE_EX A " +
            " left join INFORMATION_DATA_DIRECTORY_EX B on A.data_source_id =  B.id "
            + " @@@ )";

    @Override
    public GridView searchList(String queryParam, String dataSourceIds, String queryType, String queryDirId, Integer page, Integer size) {
        StringBuilder sbTable = new StringBuilder(" where 1=1 ");
        StringBuilder sbColumn = new StringBuilder(" where 1=1 ");
        List<Object> str = new ArrayList<>();
        //获取当前用户的所有数据源
        List<String> authDataSourceIdList = informationDataDirExService.getDataSourceId();
        if (StringUtils.isNotBlank(dataSourceIds)){
            str.add(Arrays.asList(dataSourceIds.split(",")));
            sbTable.append(" and A.data_source_id in ? ");
            sbColumn.append(" and A.data_source_id in ? ");
        }else {
            str.add(authDataSourceIdList);
            sbTable.append(" and A.data_source_id in ? ");
            sbColumn.append(" and A.data_source_id in ? ");
        }

        if (StringUtils.isNotBlank(queryParam)){  // '%cd_%'    '%cd/_%' escape '/'
            //_转义
            if (queryParam.contains("_")){
                queryParam = queryParam.replace("_", "/_");
            }
            str.add("%" + queryParam.toLowerCase() + "%");
            str.add("%" + queryParam.toLowerCase() + "%");
            if ("1".equals(queryType)){
                sbTable.append(" and (lower(A.en_name) like ? escape '/' or lower(A.ch_name) like ? escape '/' ) ");
            }else if ("2".equals(queryType)){
                sbColumn.append(" and (lower(C.en_name) like ? escape '/' or lower(C.ch_name) like ? escape '/' ) ");
            }else {
                // ### 代表字段   #### 代表表
                sbTable.append(" and (lower(A.en_name) like ? escape '/'  or lower(A.ch_name) like ? escape '/' ) ");
                sbColumn.append(" and (lower(C.en_name) like ? escape '/' or lower(C.ch_name) like ? escape '/' ) ");
            }
        }
        //查询目录
        if (StringUtils.isNotBlank(queryDirId)) {
            List<String> dirIdList = informationDataTableService.getDirIdList(queryDirId);
            str.add(dirIdList);
            sbTable.append(" and A.dir_id in ? ");
            sbColumn.append(" and A.dir_id in ? ");
        }
        Object[] objects1;
        //查询类型
        String sql;
        if ("1".equals(queryType)) { //查询表
            sbTable.append(" order by A.en_name asc, B.id asc");
            sql = new StringBuilder(TABLE_SQL).append(sbTable).toString();
            objects1 = str.toArray();
        } else if ("2".equals(queryType)) { //查询字段
            sbColumn.append(" order by A.en_name asc, C.en_name asc , B.id asc");
            sql = new StringBuilder(COLUMN_SQL).append(sbColumn).toString();
            objects1 = str.toArray();
        } else { //查询表和字段
            String table = sbTable.append(" order by A.en_name asc, B.id asc").toString();
            String column = sbColumn.append(" order by A.en_name asc, C.en_name asc , B.id asc").toString();
            String s1 = TABLE_AND_COLUMN_SQL.replaceAll("###", column);
            sql = s1.replaceAll("@@@", table);
            List<Object> list = new ArrayList<>();
            list.addAll(str);
            list.addAll(str);
            objects1 = list.toArray();
        }
        //分页
        PageAble pageAble = PageAble.createPage(page, size);
        //查询
        GridView gridMap = baseDao.findByNativeSQLToGridMap(sql, objects1, pageAble);
        List<?> objects = gridMap.getRows();
        JSONArray jsonArray = MapToBeanUtils.covertArray(JSONArray.parseArray(JSON.toJSONString(objects, SerializerFeature.WriteMapNullValue)));
        gridMap.setRows(jsonArray);
        return gridMap;
    }
}
